package com.chensheng.controller;

import com.chensheng.dao.ProductCategoryDAO;
import com.chensheng.dto.CategoryProductsDTO;
import com.chensheng.dto.ProductInfoDTO;
import com.chensheng.model.ProductCategory;
import com.chensheng.model.ProductInfo;
import com.chensheng.service.ProductCategorySercvice;
import com.chensheng.service.ProductInfoService;
import com.chensheng.dto.ResultDTO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:ChenSheng
 * @Description:
 * @Date: Created in 上午 8:01 2018/5/14 0014
 */
@RestController
@RequestMapping("/buyer/product")
public class BuyerProductController {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private ProductCategorySercvice productCategorySercvice;

    @GetMapping("/list")
    public ResultDTO list(){
        List<ProductInfo> productInfoList = productInfoService.findAllInSale();

        List<Integer> categoryTypeList = productInfoList.stream().
                map(e->e.getCategoryType()).distinct().collect(Collectors.toList());

        List<ProductCategory> productCategoryList = productCategorySercvice.findByTypeList(categoryTypeList);

        List<CategoryProductsDTO> categoryProductsDTOList = new ArrayList<>();
        for(ProductCategory productCategory : productCategoryList){
            CategoryProductsDTO categoryProductsDTO = new CategoryProductsDTO();
            categoryProductsDTO.setCategoryName(productCategory.getCategoryName());
            categoryProductsDTO.setCategoryType(productCategory.getCategoryType());

            /*List<ProductInfoDTO> productInfoDTOList = new ArrayList<>();
            List<ProductInfo> productInfoList1 = productInfoList.stream()
                    .filter(e->e.getCategoryType().equals(productCategory.getCategoryType())).collect(Collectors.toList());*/

            List<ProductInfoDTO> productInfoDTOList = new ArrayList<>();
            for (ProductInfo productInfo : productInfoList){
                if(productInfo.getCategoryType().equals(productCategory.getCategoryType())){
                    ProductInfoDTO productInfoDTO = new ProductInfoDTO();
                    BeanUtils.copyProperties(productInfo, productInfoDTO);
                    productInfoDTOList.add(productInfoDTO);
                }
            }
            categoryProductsDTO.setProductInfoDTOList(productInfoDTOList);
            categoryProductsDTOList.add(categoryProductsDTO);
        }

        return ResultDTO.success(categoryProductsDTOList);
    }

}
